package tech.yunjing.log.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import tech.yunjing.base.core.common.BaseResult;
import tech.yunjing.base.core.common.Constants;
import tech.yunjing.base.core.common.persistence.Page;
import tech.yunjing.base.core.dao.redis.RedisTemplateUtil;
import tech.yunjing.log.dao.ApplicationLogDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author miou
 *         Created by FYX on 2017/2/14 0014.
 */
@Service
public class ApplicationLogService {

    @Autowired
    private ApplicationLogDao applicationLogDao;
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    public void save(JSONObject log) {
        applicationLogDao.save(log);
    }


    /**
     * 获取日志通过应用名
     * @param name
     * @return
     */
    public BaseResult findByName(String name) {
        try {
            List<JSONObject> list = applicationLogDao.findAll(name);
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, list);
        } catch (Exception e) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
    }

    /**
     * 获取日志通过应用名
     * @param name
     * @return
     */
    public BaseResult findByNameByPage(String name,int pno,int psize) {
        try {
            List<JSONObject> list = applicationLogDao.findAllByPage(name,pno,psize);
            Page<JSONObject> page = new Page<>(pno,psize);
            page.setCount(applicationLogDao.count(name));
            page.setList(list);
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, page);
        } catch (Exception e) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
    }
    /**
     * 获取应用名
     * @return
     */
    public BaseResult findAllService() {
        try {
            Map<Object, Object> map = redisTemplateUtil.getHashMap(Constants.REDIS_SERVICES_LIST_PRFIX,Constants.REDIS_SERVICES_LIST_KEY);
            List<String> list = new ArrayList<>();
            if (map!=null){
                for (Object o:map.keySet()){
                    list.add(o.toString());
                }
            }
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, list);
        } catch (Exception e) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
    }


}

